/*
 * 上海远境文化传媒有限公司 版权所有
 */
package helper;

import play.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * 树形数据Helper.
 */
public class TreeHelper {


    /**
     * 返回树形结构的结果.
     * @param converter 如果使用了缓存，可能会造成树形节点重复.
     */
    public static <T, V> List<V> generateTreeStruct(List<T> inputList, Function<T, V> converter,
                                                    Function<T, T> parentMapper, Function<T, String> idMapper,
                                                    BiConsumer<V, V> addChildMethod) {
        List<V> result = new ArrayList<>();

        Map<String, V> resultMap = new ConcurrentHashMap<>();

        for (T t : inputList) {
            V v = converter.apply(t);
            resultMap.put(idMapper.apply(t), v);  //按ID保存结果对象
        }

        for (T t : inputList) {
            V v = resultMap.get(idMapper.apply(t)); //按ID找已经保存的对象
            T parent = parentMapper.apply(t);

            if (parent == null) {
                result.add(v);
            } else {
                V vParent = resultMap.get(idMapper.apply(parent)); //按ID找已经保存的父对象
                if (vParent != null) {
                    addChildMethod.accept(vParent, v);
                }
            }
        }
        Logger.info("LOG73493: generateTreeStruct input.size=%s, result.size=%s", inputList.size(), result.size());

        return result;
    }

}
